﻿#include "progressscreenshotthread.h"
#include <QBuffer>
#include <QDebug>
#include <QFileInfo>
#include <QFileIconProvider>
#include <progress.h>

ProgressScreenshotThread::ProgressScreenshotThread(QObject *parent) : QThread(parent)
{
    moveToThread(this);
    openScreenshot = false;
}

ProgressScreenshotThread::~ProgressScreenshotThread()
{
    qDebug() << __FUNCTION__;
    stop();
    quit();
    wait();
}

void ProgressScreenshotThread::stop()
{
    isRun = false;
}

void ProgressScreenshotThread::packProgressScreenshotData(uint64_t progressId, QPixmap pixmap)
{
    QByteArray pixmapByteArray;
    QBuffer buffer(&pixmapByteArray);
    buffer.open(QIODevice::WriteOnly);
    pixmap.save(&buffer,"png",70);// 压缩质量70%以节省内存[6](@ref)
    buffer.close();
    signal_progressScreenshotData(progressId,pixmapByteArray);
}

void ProgressScreenshotThread::setOpenScreenshot(bool value)
{
    openScreenshot = value;
}

void ProgressScreenshotThread::run()
{
    isRun = true;
    progressManage.enableDebugPriv();
    QList<Progress> progressList;
    QFileIconProvider iconProvider;

    while (isRun){
        if(!progressService.getList(progressList)){
            for(int sleep_time = 50; sleep_time > 0 && isRun; sleep_time --){
                QThread::msleep(10);
            }
            qCritical() << "获取进程列表失败！";
            continue;
        }
        for(int i=0;i<progressList.size() && isRun;i++){
            QThread::msleep(10);
            QPixmap cachedPixmap;
            if (openScreenshot) {
                DWORD pid;
                string progressPath = progressList.at(i).getPath().toStdString();
                if (progressManage.getProcessIdByPath(progressPath, pid)) {
                    QVector<QPixmap> pixmaps = progressScreenshot.getScreenshotByPID(pid);
                    if (!pixmaps.isEmpty()) {
                        cachedPixmap = pixmaps.first();
                    }
                }
            }
            if (cachedPixmap.isNull()) {
                QFileInfo fileInfo(progressList.at(i).getPath());
                if (fileInfo.exists()) {
                    cachedPixmap = iconProvider.icon(fileInfo).pixmap(32, 32);
                }
            }
            if (!cachedPixmap.isNull()) {
                packProgressScreenshotData(progressList.at(i).getId(), cachedPixmap);
            }
        }
        for(int sleep_time = 50; sleep_time > 0 && isRun; sleep_time --){
            QThread::msleep(10);
        }
    }
}
